<template>
  <div class="knowledge">
    <div class="content-outer">
      <Block class="content-head">
        <BiForm style="margin-left:-15px;">
          <DateSelect
            label="选择日期"
            :clearable="false"
            :default-value="[requestData.start_time,requestData.end_time]"
            @result="resultDate"
          />
        </BiForm>
        <!-- 列表 -->
        <div class="receptionlist rowFlex spaceBetween">
          <div class="receptionlistItem flex1">
            <div class="title rowFlex columnCenter">
              <svg-icon
                icon-class="message2"
                class="icon"
              />
              客服接待数据
            </div>
            <div class="dataContent rowFlex">
              <div class="dataContentItem flex1">
                <div class="subTitle">接待人数</div>
                <div class="dataContentItemNum">{{ numFormat(receptionInfo.customer_member_num) }}</div>
              </div>
              <div class="dataContentItem flex1">
                <div class="subTitle">接待次数</div>
                <div class="dataContentItemNum">{{ numFormat(receptionInfo.customer_num) }}</div>
              </div>
            </div>
          </div>
          <div class="receptionlistItem flex1  border">
            <div class="title rowFlex columnCenter">
              <svg-icon
                icon-class="kf"
                class="icon"
              />
              转接人工数据
            </div>
            <div class="dataContent rowFlex">
              <div class="dataContentItem flex1">
                <div class="subTitle">接待人数</div>
                <div class="dataContentItemNum">{{ numFormat(receptionInfo.artificial_member_num) }}</div>
              </div>
              <div class="dataContentItem flex1">
                <div class="subTitle">接待次数</div>
                <div class="dataContentItemNum">{{ numFormat(receptionInfo.artificial_num) }}</div>
              </div>
            </div>
          </div>
        </div>
      </Block>
      <Block class="content-table columnFlex">
        <el-tabs
          v-model="app_type"
          class="tabs"
          @tab-click="tabChange"
        >
          <el-tab-pane
            label="微信小程序"
            name="1"
          ></el-tab-pane>
          <el-tab-pane
            label="抖音小程序"
            name="2"
          ></el-tab-pane>
        </el-tabs>
        <div
          class="rowFlex rowEnd addNewAnswer"
        >
          <el-button
            type="primary"
            @click="addNewAnswer"
          >新建问答</el-button>
        </div>

        <div class="table-table">
          <BiTable
            ref="knowTable"
            :loading="loading"
            :data="tableData"
            size="medium"
            row-key="id"
            :column="tableColums"
            fixed="sticky"
            fixed-offset="50"

            :auto-scroll="false"

            @pagination="handlePageChange"
          >
            <!--
            pagination
            layout="total, prev, pager, next"
            :total="page_info.total"
            :page.sync="page_info.page"
            :limit.sync="page_info.page_size" -->
            <template v-slot:problem="{ row }">
              <div class="images rowFlex columnCenter">
                <SvgIcon
                  icon-class="drag2"
                  class="drag"
                  style="font-size: 14px; margin: -1px 3px 0 0; width: 20px"
                ></SvgIcon>
                <p class="problemTitle">{{ row.problem }}</p>
              </div>
            </template>
            <template v-slot:answer="{ row }">
              <div class="answer rowFlex columnCenter">
                <el-popover
                  placement="right"
                  trigger="click"
                >
                  <div
                    class="popoverContent"
                    style="width:400px;max-height:500px;overflow-y:auto;overflow-x:hidden;text-align:left;"
                  >
                    <div
                      class="answerContnt"
                      v-html="removeImgAltAttributes(row.answer)"
                    ></div>
                  </div>
                  <el-button
                    slot="reference"
                    type="text"
                    style="margin-left:5px;"
                    size="medium"
                  >预览</el-button>
                </el-popover>
              </div>
            </template>
            <template v-slot:status="{row}">
              <div>
                <el-switch
                  v-model="row.status"
                  active-value="1"
                  inactive-value="2"
                  @change="switchStatus(row)"
                >
                </el-switch>
              </div>
            </template>
            <template v-slot:zip="{ row }">
              <div class="rowFlex">
                <el-button
                  type="text"
                  size="medium"
                  @click="edit(row)"
                >编辑</el-button>

                <el-popconfirm
                  icon="el-icon-info"
                  icon-color="red"
                  style="margin-left:10px;"
                  :title="`确认复制到${app_type==1?'抖音小程序':'微信小程序'}么？`"
                  @confirm="copy(row)"
                >
                  <el-button
                    slot="reference"
                    type="text"
                    size="medium"
                  >复制</el-button>
                </el-popconfirm>
                <el-popconfirm
                  icon="el-icon-info"
                  icon-color="red"
                  style="margin-left:10px;"
                  title="确定删除吗？"
                  @confirm="delRow(row)"
                >
                  <el-button
                    slot="reference"
                    type="text"
                    size="medium"
                  >删除</el-button>
                </el-popconfirm>
              </div>
            </template>
          </BiTable>
        </div>
      </Block>
    </div>
    <!-- 新增问答 -->
    <BiDrawer
      v-if="addKnowledge"
      v-model="addKnowledge"
      :drawer-title="rowInfo.id?'编辑问答':'新建问答'"
      :row-info="rowInfo"
      :component="addKnowledgeVue"
      drawer-size="600px"
      @ok="onSubmit"
    ></BiDrawer>
  </div>
</template>

<script>
import SvgIcon from '@/components/SvgIcon/index.vue'
import Sortable from 'sortablejs'
import DateSelect from '@/common/component/form/dateSelect.vue'
import { numFormat, debounce } from '@/utils/index'
import { reception, answerList, answerSave, answerSort, answerDel, answerSwitch } from '@/api/knowLedge'
import addKnowledgeVue from './component/addKnowledge.vue'
export default {
  components: {
    DateSelect,
    addKnowledgeVue,
    SvgIcon
  },
  data() {
    return {
      addKnowledge: false,
      rowInfo: {},
      loading: false,
      addKnowledgeVue: addKnowledgeVue,
      receptionInfo: {
        customer_num: 0,
        customer_member_num: 0,
        artificial_num: 0,
        artificial_member_num: 0
      },
      app_type: '1',
      requestData: {
        start_time: this.$moment().subtract(7, 'days').format('YYYY-MM-DD'),
        end_time: this.$moment().format('YYYY-MM-DD')
      },
      tableData: [],
      page_info: {
        page: 1,
        page_size: 20,
        total: 0
      },
      tableColums: [
        {
          label: '问题',
          prop: 'problem',
          minWidth: 350,
          slotScope: true
        },
        {
          label: '回复答案',
          prop: 'answer',
          minWidth: 120,
          slotScope: true
        },
        {
          label: '小程序类型',
          prop: 'pay_up',
          renderHeader: (h, { row }) => {
            return (
              <div>
                小程序类型
                <el-tooltip class='item' effect='dark' placement='top'>
                  <div slot='content' class='tooltipLine'>
                    应用该问题的小程序类型
                  </div>
                  <i class='el-icon-question' style='margin-left:5px;color:#86909C;'></i>
                </el-tooltip>
              </div>
            )
          },
          render: (h, { row }) => {
            return <span>{row.app_type == 1 ? '微信小程序' : '抖音小程序'} </span>
          },
          minWidth: 120
        },
        {
          label: '生效状态',
          prop: 'status',
          minWidth: 100,
          slotScope: true
        },
        {
          label: '累计咨询次数',
          prop: 'total_num',
          minWidth: 100,
          render: (h, { row }) => {
            if (row.total_num) {
              return <span>{numFormat(row.total_num)} </span>
            } else {
              return <span>{numFormat(0)} </span>
            }
          }
        },
        {
          label: '累计咨询人数',
          prop: 'total_member_num',
          minWidth: 100,
          render: (h, { row }) => {
            if (row.total_member_num) {
              return <span>{numFormat(row.total_member_num)} </span>
            } else {
              return <span>{numFormat(0)} </span>
            }
          }
        },
        {
          label: '操作',
          prop: 'zip',
          minWidth: 120,
          slotScope: true
        }
      ]
    }
  },
  mounted() {
    this.$AccessReport.report('zhangyu-knowledge', ['全部', '知识库', '知识库'])
    this.answerList()
    this.requestReceptionInfo()
    this.$nextTick(() => {
      this.drag()
    })
  },
  methods: {
    removeImgAltAttributes(htmlString) {
      return htmlString.replace(/<img[^>]*? title="[^"]*"[^>]*>/gi, function(match) {
        return match.replace(/ title="[^"]*"/gi, '')
      })
    },
    addNewAnswer() {
      this.rowInfo = {}
      this.rowInfo.app_type = [this.app_type]
      this.addKnowledge = true
    },
    onSubmit() {
      this.answerList()
    },
    drag() {
      const _this = this
      // 首先获取需要拖拽的dom节点
      const el1 = this.$refs.knowTable.$el.querySelectorAll(
        '.el-table__body-wrapper > table > tbody'
      )[0]
      Sortable.create(el1, {
        disabled: false, // 是否开启拖拽
        ghostClass: 'sortable-ghost', // 拖拽样式
        animation: 150, // 拖拽延时，效果更好看
        group: {
          // 是否开启跨表拖拽
          pull: false,
          put: false
        },
        onEnd({ newIndex, oldIndex }) {
          // 修改data中的数组，
          const targetRow = _this.tableData.splice(oldIndex, 1)[0]
          _this.tableData.splice(newIndex, 0, targetRow)
          const arr = []
          _this.tableData.forEach((item, index) => {
            arr.push({
              id: item.id,
              sort: index
            })
          })
          _this.onWallCoverSort(arr)
        },
        onChoose: function (/** Event*/ evt) {
          console.log(evt)
        }
      })
    },
    async onWallCoverSort(arr) {
      const res = await answerSort({
        list: arr,
        app_type: this.app_type
      })
      if (res.status_code == 1) {
        this.answerList()
      }
    },
    resultDate(data) {
      this.requestData.start_time = data.start_date
      this.requestData.end_time = data.end_date
      this.requestReceptionInfo()
    },
    numFormat(num) {
      return numFormat(num)
    },
    async delRow(row) {
      const res = await answerDel({ app_type: this.app_type, id: row.id })
      if (res.status_code === 1) {
        this.$message.success(res.msg)
        this.answerList()
      }
    },
    async copy(row) {
      console.log(row, 'row')
      const { app_type, problem, answer, id } = row
      const data = {
        app_type: app_type == 1 ? [2] : [1],
        problem,
        answer
      }
      const res = await answerSave(data)
      if (res.status_code === 1) {
        this.$message.success(res.msg)
      }
    },
    edit(row) {
      this.rowInfo = row
      this.addKnowledge = true
    },
    async requestReceptionInfo() {
      const res = await reception(this.requestData)
      if (res.status_code === 1) {
        this.receptionInfo = res.data.data
      }
    },
    async switchStatus(row) {
      const res = answerSwitch({ id: row.id, status: row.status, app_type: this.app_type })
      if (res.status_code === 1) {
        this.$message.success(res.msg)
      }
    },
    async answerList() {
      this.loading = true
      try {
        const res = await answerList({ app_type: this.app_type })
        this.loading = false
        if (res.status_code === 1) {
          this.tableData = res.data.data
          res.data.page_info ? this.page_info = res.data.page_info : ''
        }
      } catch (error) {
        this.loading = false
      }
    },
    tabChange(value) {
      // 切换代码
      this.answerList()
    },
    handlePageChange(page) {
      this.page_info.page = page.page
      this.clickSearch()
    }
  }
}
</script>
<style lang="scss" scoped>
.knowledge {
  width: 100%;
  height: auto;
  .receptionlist {
    width: 100%;
    height: auto;
    margin-top: 0px;
    padding-bottom: 20px;
    .border {
      border-left: 1px solid #e5e6eb;
      padding-left: 20px;
    }
    .receptionlistItem {
      .title {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 16px;
        color: #1d2129;
        text-align: left;
        margin-bottom: 15px;
        .icon {
          font-size: 16px;
        }
      }
      .icon {
        margin-right: 5px;
      }
      .dataContent {
        width: 100%;
        .dataContentItem {
          .subTitle {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 14px;
            color: #4e5969;
            line-height: 20px;
            text-align: left;
          }
          .dataContentItemNum {
            font-family: PingFangSC, PingFang SC;
            font-weight: 500;
            font-size: 28px;
            color: #1d2129;
            line-height: 40px;
            text-align: left;
            font-style: normal;
          }
        }
      }
    }
  }
  .problemTitle {
    width: 100%;
    overflow: hidden;
    white-space: nowrap; /* 防止文字换行 */
    text-overflow: ellipsis; /* 超出部分显示省略号 */
  }

}
.addNewAnswer{
  position: relative;
  top: -60px;
}
.answerContnt{
  ::v-deep video {
    display: block;
  }
  ::v-deep img{
    max-width: 400px;
  }
  ::v-deep video{
    max-width: 400px;
    max-height: 600px;
  }
}
.table-table{
  margin-top: -30px;
}
</style>